

import java.io.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import client.*;
import common.*;
import entity.*;

/**
 * This class constructs the UI for a chat client.  It implements the
 * chat interface in order to activate the display() method.
 * Warning: Some of the code here is cloned in ServerConsole 
 *
 * @author Omri Barda		039725890
 * @author Amit Joseph		034608547
 * @author Gilad Shpigel  	300162393
 * @author Elad Elbaz		040539959
 * @author Natali Kazav		038109401
 * @version May 2012
 */
public class ClientConsole implements ChatIF 
{
  //Class variables *************************************************
  
  /**
   * The default port to connect on.
   */
  final public static int DEFAULT_PORT = 5555;
  
  //Instance variables **********************************************
  
  /**
   * The instance of the client that created this ConsoleChat.
   */
  ChatClient client;
  ArrayList<String> message;
  
  //Constructors ****************************************************

  /**
   * Constructs an instance of the ClientConsole UI.
   *
   * @param host The host to connect to.
   * @param port The port to connect on.
   */
  public ClientConsole(String host, int port) 
  {
    try 
    {
      client= new ChatClient(host, port, this);
    } 
    catch(IOException exception) 
    {
      System.out.println("Error: Can't setup connection!"
                + " Terminating client.");
      System.exit(1);
    }
  }

  
  //Instance methods ************************************************
  
  /**
   * This method waits for input from the console.  Once it is 
   * received, it sends it to the client's query handler.
   */
  public void accept() 
  {
	String option;
	try
    {
      BufferedReader fromConsole = new BufferedReader(new InputStreamReader(System.in));
      
      while (true) 
      {
        option = printMainMenu(fromConsole);
    	switch(option.charAt(0))
    	{
    		case '1': 	//create
    			createQuestion(fromConsole);
    			break;
    		case '2':	//delete
    			deleteQuestion(fromConsole);
    			break;
    		case '3':	//print
    		//	printQuestion();
    			getQuestion(fromConsole);
    			break;
    		case '4':	//exit
    			System.exit(0);
    			break;
    		default:	//any other stupid char
    			Perror.pError("Wrong option! choose again.\n");
    			break;
    	}
    	Thread.sleep(300);
      }
    } 
    catch (Exception ex) 
    {
      System.out.println
        ("Unexpected error while reading from console!");
    }
  }

	/**
	 * Getting question from the Database.
	 *
	 * @param fromConsole-The query for execution.
	 */	

private void getQuestion(BufferedReader fromConsole) throws IOException, InterruptedException 
  {
		Question q = new Question();
		String input;
		
		System.out.println("-= GET QUESTION =-");
		
		do {
				System.out.println("enter question ID:\n");
				input = fromConsole.readLine();
				if (input.length()!=5)
					Perror.pError("ID is invalid.\n please enter a 5 digit number.");
		}while (input.length()!=5);
		q.setqID(input);
		System.out.println("getting question... please wait!");
		client.handleQuestionFromClient(q,Question.GET);

  }
/**
 * Deleting question from the Database.
 *
 * @param fromConsole-The query for execution.
 */	

private void deleteQuestion(BufferedReader fromConsole) throws IOException 
  {
		Question q = new Question();
		String input;
		
		System.out.println("-= DELETE QUESTION =-");
		
		do {
				System.out.println("enter question ID:\n");
				input = fromConsole.readLine();
				if (input.length()!=5)
					Perror.pError("ID is invalid.\n please enter a 5 digit number.");
		}while (input.length()!=5);
		q.setqID(input);
		System.out.println("deleting question... please wait!");
		client.handleQuestionFromClient(q,Question.DELETE);
  }

/**
 * Adding question to the Database.
 *
 * @param fromConsole-The query for execution.
 */	
private void createQuestion(BufferedReader fromConsole) throws IOException 
  {
	Question q = new Question();
	String input;
	
	System.out.println("-= CREATE QUESTION =-");
	
	do {
			System.out.println("enter question ID:\n");
			input = fromConsole.readLine();
			if (input.length()!=5)
				Perror.pError("ID is invalid.\n please enter a 5 digit number.");
	}while (input.length()!=5);
	q.setqID(input);
	
	System.out.println("enter instructions:\n");
		input = fromConsole.readLine();
		q.setqInstructions(input);
	
	System.out.println("enter the question:\n");
		input = fromConsole.readLine();
		q.setqText(input);
		
	System.out.println("enter the correct answer::\n");
		input = fromConsole.readLine();
		q.setCorrectAns(input);
		
	System.out.println("enter answer A:\n");
		input = fromConsole.readLine();
		q.setAnswerA(input);
	
	System.out.println("enter answer B:\n");
		input = fromConsole.readLine();
		q.setAnswerB(input);
	
	System.out.println("enter answer C:\n");
		input = fromConsole.readLine();
		q.setAnswerC(input);
	
		/*using login information */
		q.setqCreator("my name");
		q.setqDate(Calendar.getInstance().getTime());
		
	System.out.println("creating question... please wait!");
	client.handleQuestionFromClient(q,Question.CREATE);	
	
  }
  
  
/**
 * Printing the client Main Menu.
 *
 * @param fromConsole-The query for execution.
 */	
  
private String printMainMenu(BufferedReader fromConsole) throws IOException 
  {
	  System.out.println("Main Menu:");
	  System.out.println("1) Create new question.");
	  System.out.println("2) delete question.");
	  System.out.println("3) print question.");
	  System.out.println("4) quit.");
	  System.out.println("\nplease choose an option...");
	  return(fromConsole.readLine());
	  
  }

/**
   * This method overrides the method in the ChatIF interface.  It
   * displays a message onto the screen.
   *
   * @param message The string to be displayed.
   */
  public void display(String message) 
  {
    System.out.println("> " + message);
  }

  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of the Client UI.
   *
   * @param args[0] The host to connect to.
   */
  public static void main(String[] args) 
  {
    String host = "";
    int port = 0;  //The port number
    
    try
    {
      host = args[0];
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
    	//host = "85.64.244.174"; // gilad's IP 
    	host = "127.0.0.1";
    }
    ClientConsole chat= new ClientConsole(host, DEFAULT_PORT);
    chat.accept();  //Wait for console data
  }
}
//End of ConsoleChat class
